package com.iot.inclinometer.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.iot.inclinometer.R;
import com.iot.inclinometer.dao.IBaseInfoDao;
import com.iot.inclinometer.dao.ICorrectDataInfoDao;
import com.iot.inclinometer.dao.IDataInfoDao;
import com.iot.inclinometer.dao.IObserveInfoDao;
import com.iot.inclinometer.dao.impl.BaseInfoDaoImpl;
import com.iot.inclinometer.dao.impl.CorrectDataInfoDaoImpl;
import com.iot.inclinometer.dao.impl.DataInfoDaoImpl;
import com.iot.inclinometer.dao.impl.ObserveInfoDaoImpl;
import com.iot.inclinometer.pojo.BaseInfo;
import com.iot.inclinometer.pojo.CorrectDataInfo;
import com.iot.inclinometer.pojo.ObserveInfo;
import com.iot.inclinometer.util.Common;
import com.iot.inclinometer.util.ContextApplication;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * “绘图”页面
 * 
 * @author ZSL
 * 
 */
public class PaintProUI extends Activity /*implements View.OnTouchListener */{
	private TextView titleView;		//显示标题(产品型号)
	private ImageView newProBtn;
	private ImageView outputBtn;
	private ImageView oldProBtn;
	/** 上传 */
	private ImageView uploadDBBtn;
	private ImageView configurationBtn;
	private ImageView exitBtn;
	
	private String model=null;    //产品型号
	
	private LinearLayout chatLoc;
	/** 工程名称控件 */
	private Spinner projectNameSp = null;
	/** 工点名称空间 */
	private Spinner itemNameSp = null;
	/** 钻孔编号控件 */
	private Spinner drillNumSp = null;

	private EditText startTime = null;
	private EditText endTime = null;
	//时间选择器
	private TimePickerView pvTime;
	private Spinner errordirectionSp = null;

	private TextView view1 = null;//四个view用来显示：里程桩号、位置描述、坐标、孔深；若其中某个为空，则不显示它
	private TextView view2 = null;
	private TextView view3 = null;
	private TextView view4 = null;

	private Button paintChartBtn = null;

	private ArrayAdapter<String> projectAdapter = null;

	private ArrayAdapter<String> itemAdapter = null;

	private ArrayAdapter<String> drillAdapter = null;

	private IBaseInfoDao baseInfoDao = new BaseInfoDaoImpl(this);
	private IObserveInfoDao observeInfoDao = new ObserveInfoDaoImpl(this);
	private IDataInfoDao dataInfoDao = new DataInfoDaoImpl(this);
	private ICorrectDataInfoDao correctDataInfoDao = new CorrectDataInfoDaoImpl(this);
	
	private double currentDepth = 0;
	private int currentBaseId = 0;
	
	private InputMethodManager inputMethodManager;       //控制键盘隐藏

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.paint_pro_activity);
		inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		SharedPreferences sharedPreferences= ContextApplication.getAppContext().getSharedPreferences("configuration",0);
		model=sharedPreferences.getString("Model","");
		initView();
		initMenu();
		setBtnListener();
	}
    /*
     * 初始化控件
     * */
	private void initView() {
		titleView=(TextView) findViewById(R.id.tv_top_title); 	//初始化标题
		String newTitle = Common.isEmpty(model)?"":"("+model+")";
		titleView.setText(titleView.getText()+ newTitle);
		
		oldProBtn = (ImageView) findViewById(R.id.old_pro_btn);
		newProBtn = (ImageView) findViewById(R.id.new_pro_btn);
		outputBtn = (ImageView) findViewById(R.id.output_btn);
		uploadDBBtn = (ImageView) findViewById(R.id.uploaddbToServer_btn);
		configurationBtn = (ImageView) findViewById(R.id.configuration_btn);
		exitBtn = (ImageView) findViewById(R.id.exit_btn);
		chatLoc = (LinearLayout) findViewById(R.id.chatLocation);

		// -----------初始化需要赋值的控件-------------------
		projectNameSp = (Spinner) findViewById(R.id.project_name_spinner);
		itemNameSp = (Spinner) findViewById(R.id.item_name_spinner);
		drillNumSp = (Spinner) findViewById(R.id.drill_num_spinner);

		startTime = (EditText) findViewById(R.id.start_time);
		endTime = (EditText) findViewById(R.id.end_time);
		errordirectionSp = (Spinner) findViewById(R.id.errordirection_spinner);

		view1 = (TextView) findViewById(R.id.view1);//四个view用来显示：里程桩号、位置描述、坐标、孔深；
		view2 = (TextView) findViewById(R.id.view2);//若其中某个为空，则不显示它。
		view3 = (TextView) findViewById(R.id.view3);
		view4 = (TextView) findViewById(R.id.view4);

		paintChartBtn = (Button) findViewById(R.id.paint_chart_btn);


		//时间选择器
		pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
			@Override
			public void onTimeSelect(Date date, View v) {
				((EditText)v).setText(Common.getTime(date,"yyyy-MM-dd"));
			}
		})
				.setType(new boolean[]{true, true, true, false, false, false})
				.setLabel("年", "月", "日", "时", "分", "秒")
				.setCancelText("取消")
				.setSubmitText("确定")
				.build();
	}
    /*
     * 设置按钮的点击监听
     * */
	private void setBtnListener() {
		oldProBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(PaintProUI.this, OldProUI.class);
				startActivity(intent);
				PaintProUI.this.finish();
			}
		});
		newProBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(PaintProUI.this, NewProUI.class);
				startActivity(intent);
				PaintProUI.this.finish();
			}
		});
		outputBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(PaintProUI.this, OutputProUI.class);
				startActivity(intent);
				PaintProUI.this.finish();
			}
		});
		uploadDBBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(PaintProUI.this, UploadDBToServerUI.class);
				startActivity(intent);
				PaintProUI.this.finish();
			}
		});
		configurationBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(PaintProUI.this, ConfigurationLicenseUI.class);
				startActivity(intent);
			}
		});
		exitBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sureDialog();
			}
		});

		projectNameSp.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					initMenu2();
					initMenu3();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}

		});
		itemNameSp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					initMenu3();
				} catch (Exception exception) {
					exception.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
		drillNumSp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				try {
					initValue();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

//		startTime.setOnTouchListener(this);
//		endTime.setOnTouchListener(this);
		// gisboss 优化时间选择
		startTime.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					pvTime.show(v);
				}
				return true;
			}
		});
		endTime.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					pvTime.show(v);
				}
				return true;
			}
		});

		paintChartBtn.setOnClickListener(paintChartOnClickListener);
	}

	private OnClickListener paintChartOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			String startDate = startTime.getText().toString().trim();
			String endDate = endTime.getText().toString().trim();
			String errordirection= errordirectionSp.getSelectedItem().toString();
			String MEASURE_ANGLE_0="A0方向";
		
			
			/*
			 * 如何找到一个孔对应的所有数据呢？
			 * 1.通过四个参数，找到唯一的钻孔编号对应的基本信息记录
			 * 2.通过base_id与measurecount（还有时间）找到对应的孔号的相应的所有“0度”测量的记录集合 
			 * 	   （因为修正数据的ob_id和两组观测数据中0度观测数据的ob_id相同）
			 * 3.通过ob_Id查找对应的偏移数据集合，由errordirection决定选哪种位移
			 * 4.将集合中的数据都显示出来
			 */

			List<ObserveInfo> allObserveInfos = new ArrayList<ObserveInfo>();

			if (!(startDate.length() == 0) && !(endDate.length() == 0)) {
					 
				allObserveInfos = observeInfoDao.selectObserveInfos(
								currentBaseId, MEASURE_ANGLE_0, startDate, endDate);
				   
              } else {// 表示没有选择时间，自动绘制出该孔的所有数据
				allObserveInfos = observeInfoDao.selectObserverInfos(
						currentBaseId, MEASURE_ANGLE_0);
			}

			int _length = allObserveInfos.size() + 1;
			if (allObserveInfos.size() < 1) {
				showMsg("无数据，请选择其他条件！");
			} else {// 执行有数据的步骤
				String[] _titles = new String[_length];
				int[] _colors = new int[_length];
				PointStyle[] _styles = new PointStyle[_length];
				List<double[]> _depths = new ArrayList<double[]>();
				List<double[]> _errors = new ArrayList<double[]>();

				// 设置中轴的属性
				_titles[0] = "中轴";
				_colors[0] = Color.RED;
				_styles[0] = PointStyle.CIRCLE;
				_depths.add(new double[] { 0, currentDepth });
				_errors.add(new double[] { 0, 0 });

				int i = 1; // 定义一个指针
				for (ObserveInfo observeInfo : allObserveInfos) {
					int count=observeInfo.getCount();//获得count的次数
					_titles[i] = observeInfo.getTime();//获取观测时间
					
					List<CorrectDataInfo> correctDataInfos = correctDataInfoDao.selectDataInfos(observeInfo.getObserveId());
					
					if (correctDataInfos.size() > 0) {//correctDataInfos表有数据
						double[] depth = new double[correctDataInfos.size()];
						double[] error = new double[correctDataInfos.size()];
						if(count==1){//判断是否为第一次有效测量，第一次每个深度点的位移都输出为0，之后按数据库中的实际值输出
							int j = 0;
							// 表示至少存在一条折线的数据
							for (CorrectDataInfo correctDataInfo : correctDataInfos) {//每一个记录表示一条折线
								depth[j] = Double.parseDouble(correctDataInfo.getDepth());
								error[j] =0.0;    //第一次测量每个深度点的累计位移都为0，用于绘图
								j++;
							}
						}else{
							int j = 0;
							// 表示至少存在一条折线的数据
							for (CorrectDataInfo correctDataInfo : correctDataInfos) {// 每一个记录表示一条折线
								depth[j] = Double.parseDouble(correctDataInfo.getDepth());
								if("A方向位移".equals(errordirection)){
									error[j] = Double.parseDouble(correctDataInfo.getLx());//取出A0方向的每个深度点的累计位移，用于绘图（角度数据求得的累计位移）
								}
								if("B方向位移".equals(errordirection)){
									error[j] = Double.parseDouble(correctDataInfo.getLy()); //取出A180方向的每个深度点的累计位移，用于绘图
								}
								if("A+B方向位移".equals(errordirection)){
									error[j] = Double.parseDouble(correctDataInfo.getError());//取出每个深度点的合成累计位移，用于绘图
								}
								j++;
							}
						}						
						_depths.add(depth);
						_errors.add(error);

					} else { // 表示没有集合
						_depths.add(new double[] { 0, 0 });
						_errors.add(new double[] { 0, 0 });
					}
					i++;
				}

				for (int j = 1; j < _length; j++) {
					_colors[j] = randomColor();
					_styles[j] = PointStyle.DIAMOND;
				}

				// 调用方法将数据显示在图表上
				chatLoc.removeAllViews();
				initMeasureView(currentDepth, _titles, _depths, _errors,
						_colors, _styles);

			}

		}
	};

	/**
	 * 获得随机颜色
	 * 
	 * @return
	 */
	private int randomColor() {
		Random random = new Random();
		int r = random.nextInt(255);
		int g = random.nextInt(255);
		int b = random.nextInt(255);
		return Color.rgb(r, g, b);
	}

	/**
	 * 显示一个Toast
	 * 
	 * @param msg
	 */
	private void showMsg(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
		;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			sureDialog();
			return true;
		}
		return true;
	}

	/**
	 * 确认框
	 */
	public void sureDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确定退出程序吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// AccoutList.this.finish();
						// System.exit(1);
						android.os.Process.killProcess(android.os.Process
								.myPid());
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	/**
	 * 绘制中轴
	 */
	private void initMeasureView(double depth) {

		String[] titles = new String[] { "中轴" };// 每条曲线的名称

		List<double[]> x = new ArrayList<double[]>(); // 点集的x坐标
		List<double[]> y = new ArrayList<double[]>(); // 点集的y坐标

		x.add(new double[] { 0, depth }); // 中轴

		y.add(new double[] { 0, 0 }); // 中轴

		XYMultipleSeriesDataset dataset = buildDataset(titles, x, y);

		int[] colors = new int[] { Color.RED }; // 根据线的条数，变化
		PointStyle[] styles = new PointStyle[] { PointStyle.CIRCLE };// 根据线的条数，变化
		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles, true);

		setChartSettings(renderer, null, "深度(米)", "位移（毫米）", 0, depth, -5, 5,
				Color.RED, Color.BLUE);// 设置坐标系的参数

		View chart = ChartFactory.getLineChartView(this, dataset, renderer); // 折线图
		chart.setRotation(90.0f);
		chatLoc.addView(chart);
	}

	/**
	 * 绘制折线图
	 * 
	 * @param depth
	 *            深度
	 * @param titles
	 *            标题数组
	 * @param depths
	 *            深度数组
	 * @param errors
	 *            偏移数组
	 * @param colors
	 *            颜色数组
	 * @param styles
	 *            类型数组
	 */
	private void initMeasureView(double depth, String[] titles,
			List<double[]> depths, List<double[]> errors, int[] colors,
			PointStyle[] styles) {

		List<double[]> x = new ArrayList<double[]>(); // 点集的x坐标
		List<double[]> y = new ArrayList<double[]>(); // 点集的y坐标
		for (double[] a : depths) {
			x.add(a);
		}
		for (double[] b : errors) {
			y.add(b);
		}
		XYMultipleSeriesDataset dataset = buildDataset(titles, x, y);//折线图的坐标集

		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles, true);//折线图的样式集

		setChartSettings(renderer, null, "深度(米)", "位移（毫米）", 0, depth, -5, 5,
				Color.RED, Color.BLUE);// 设置坐标系的参数

		View chart = ChartFactory.getLineChartView(this, dataset, renderer); //显示折线图
		chart.setRotation(90.0f);
		chatLoc.addView(chart);
	}
	
	//坐标集
	protected XYMultipleSeriesDataset buildDataset(String[] titles,
			List<double[]> xValues, List<double[]> yValues) {
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

		int length = titles.length; // 有几条线
		for (int i = 0; i < length; i++) {
			XYSeries series = new XYSeries(titles[i]); // 根据每条线的名称创建
			double[] xV = (double[]) xValues.get(i); // 获取线的数据
			double[] yV = (double[]) yValues.get(i);
			int seriesLength = xV.length; // 有几个点

			for (int k = 0; k < seriesLength; k++) // 每条线里有几个点
			{
				series.add(xV[k], yV[k]);
			}

			dataset.addSeries(series);
		}

		return dataset;
	}

	//样式集
	protected XYMultipleSeriesRenderer buildRenderer(int[] colors,PointStyle[] styles, boolean fill) {
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		int length = colors.length;
		for (int i = 0; i < length; i++) {
			XYSeriesRenderer r = new XYSeriesRenderer();
			r.setColor(colors[i]);
			r.setPointStyle(styles[i]);
			r.setFillPoints(fill);
			renderer.addSeriesRenderer(r);
		}
		return renderer;
	}

	/**
	 * 设置图表的属性
	 * 
	 * @param renderer
	 * @param title
	 * @param xTitle
	 * @param yTitle
	 * @param xMin
	 * @param xMax
	 * @param yMin
	 * @param yMax
	 * @param axesColor
	 * @param labelsColor
	 */
	protected void setChartSettings(XYMultipleSeriesRenderer renderer,
			String title, String xTitle, String yTitle, double xMin,
			double xMax, double yMin, double yMax, int axesColor,
			int labelsColor) {
		renderer.setChartTitle(title);
		renderer.setXTitle(xTitle);
		renderer.setYTitle(yTitle);
		//renderer.setXLabelsAlign(Align.CENTER);/*/////*/
		//renderer.setYLabelsAlign(Align.CENTER);/*/////*/
		renderer.setXAxisMin(xMin);
		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);
		renderer.setAxesColor(axesColor);
		 //renderer.setMargins(new int[] {2, 2, 2,2}); // 图形4边距/********/
		//设置不可拖动
		renderer.setPanEnabled(false,true);
		// 标题颜色
		renderer.setLabelsColor(labelsColor);
		// 设置刻度的颜色
		renderer.setXLabelsColor(Color.BLUE);
		renderer.setYLabelsColor(0, Color.BLUE);
		// 设置图标内部颜色
		renderer.setApplyBackgroundColor(true);
		// renderer.setBackgroundColor(Color.WHITE);
		// 设置图标外部颜色
		renderer.setMarginsColor(Color.LTGRAY);
		renderer.setShowLegend(true); // 显示

	}

	/**
	 * 初始化三级联动菜单
	 */
	private void initMenu() {
		try {
			initMenu1();
			initMenu2();
			initMenu3();
		} catch (Exception e) {

		}
	}

	private void initMenu1() throws Exception {
		// ---------------------初始化项目名称-start---------------------------
		Set<String> projectNameSet = new HashSet<String>(); // 保存不重复的项目名
		List<String> projectNames = new ArrayList<String>(); // 将Set集合转成List集合,从而放入适配器

		List<BaseInfo> allBaseInfo = this.baseInfoDao.selectBaseInfos();

		for (BaseInfo baseInfo : allBaseInfo) {
			projectNameSet.add(baseInfo.getProjectName());
		}
		for (String projectName : projectNameSet) {
			projectNames.add(projectName);
		}
		Collections.sort(projectNames);//顺序排列
		// 把数组导入到ArrayList中
		projectAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, projectNames);
		projectAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 设置下拉菜单的风格
		projectNameSp.setAdapter(projectAdapter);
		// 绑定适配器
		projectNameSp.setPrompt("请选择项目名");
	}

	private void initMenu2() throws Exception {
		// **************************初始化二级联动菜单**start****************************
		String selectedProject = projectNameSp.getSelectedItem().toString();
		Set<String> allItemsSet = new HashSet<String>();
		List<String> allItemsList = new ArrayList<String>();
		List<BaseInfo> allItems = this.baseInfoDao
				.selectBaseInfos(selectedProject); // 通过选中的项目名来取得对应的记录，从而得出二级目录的数据
		for (BaseInfo baseInfo : allItems) {
			allItemsSet.add(baseInfo.getItemName());
		}
		for (String item : allItemsSet) {
			allItemsList.add(item);
		}
		Collections.sort(allItemsList);//顺序排列
		// 把数组导入到ArrayList中
		itemAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, allItemsList);
		itemAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 设置下拉菜单的风格
		itemNameSp.setAdapter(itemAdapter);
		// 绑定适配器
		itemNameSp.setPrompt("请选择工点名");
		// **************************初始化二级联动菜单**end*************************
	}

	private void initMenu3() throws Exception {
		String selectedProject = projectNameSp.getSelectedItem().toString();
		String selectedItem = itemNameSp.getSelectedItem().toString();
		Set<String> allDrillSet = new HashSet<String>();
		List<String> allDrillList = new ArrayList<String>();

		List<BaseInfo> allDrills = this.baseInfoDao.selectBaseInfos(
				selectedProject, selectedItem);
		for (BaseInfo baseInfo : allDrills) {
			allDrillSet.add(baseInfo.getDrillNum());
		}
		for (String drillNum : allDrillSet) {
			allDrillList.add(drillNum);
		}
		Collections.sort(allDrillList);//顺序排列
		drillAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, allDrillList);
		drillAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		drillNumSp.setAdapter(drillAdapter);
		drillNumSp.setPrompt("请选择钻孔编号");
		initValue();
	}

	/**
	 * 为界面上的TextView控件赋值
	 */
	private void initValue() throws Exception {
		String selectedProject = projectNameSp.getSelectedItem().toString();
		String selectedItem = itemNameSp.getSelectedItem().toString();
		String selectedDrill = drillNumSp.getSelectedItem().toString();
		BaseInfo baseInfo = this.baseInfoDao.selectBaseInfos(selectedProject,
				selectedItem, selectedDrill);
		
		String[] str=new String[]{"","","",""};
		if(!baseInfo.getMark2().equals("")||!baseInfo.getMark4().equals("")){
			str[0]="里程桩号："+baseInfo.getMark1()+baseInfo.getMark2()+baseInfo.getMark3()+baseInfo.getMark4()+"(m)";
		}
		if(!baseInfo.getLoc().equals("")){
			str[1]="位置描述："+baseInfo.getLoc();
		}
		if(!baseInfo.getX().equals("")||!baseInfo.getY().equals("")){
			str[2]="坐        标："+"X="+baseInfo.getX()+","+"Y="+baseInfo.getY();
		}
		str[3]="孔        深："+baseInfo.getDepth()+"(m)";
		//把非空的移到数组的前面位置
		String[] strNotNull=new String[]{"","","",""};
		for(int i=0,j=0;i<str.length;i++){
			if(!str[i].equals("")){
				strNotNull[j]=str[i];
				j++;
			}
		}
		view1.setText(strNotNull[0]);
		view2.setText(strNotNull[1]);
		view3.setText(strNotNull[2]);
		view4.setText(strNotNull[3]);
		
		currentDepth =Double.parseDouble(baseInfo.getDepth());
		currentBaseId = baseInfo.getBaseId();

		chatLoc.removeAllViews();
		initMeasureView(currentDepth);
	}

//	/**
//	 * 监听点击日期edit的方法，然后弹出日期选择器
//	 */
//
//	public boolean onTouch(View v, MotionEvent event) {
//		if (event.getAction() == MotionEvent.ACTION_DOWN) {
//			AlertDialog.Builder builder = new AlertDialog.Builder(this);
//			View view = View.inflate(this, R.layout.date_dialog, null);
//			final DatePicker datePicker = (DatePicker) view
//					.findViewById(R.id.date_picker);
//			builder.setView(view);
//
//			Calendar cal = Calendar.getInstance();
//			cal.setTimeInMillis(System.currentTimeMillis());
//			datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
//					cal.get(Calendar.DAY_OF_MONTH), null);
//
//			if (v.getId() == R.id.start_time) {
//				final int inType = startTime.getInputType();
//				startTime.setInputType(InputType.TYPE_NULL);
//				startTime.onTouchEvent(event);
//				startTime.setInputType(inType);
//				startTime.setSelection(startTime.getText().length());
//
//				builder.setPositiveButton("确  定",
//						new DialogInterface.OnClickListener() {
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//
//								StringBuffer sb = new StringBuffer();
//								sb.append(String.format("%d-%02d-%02d",
//										datePicker.getYear(),
//										datePicker.getMonth() + 1,
//										datePicker.getDayOfMonth()));
//								startTime.setText(sb);
//								endTime.requestFocus(); // 结束选择框获得焦点
//								dialog.cancel();
//							}
//						});
//			} else if (v.getId() == R.id.end_time) {
//				final int inType = startTime.getInputType();
//				endTime.setInputType(InputType.TYPE_NULL);
//				endTime.onTouchEvent(event);
//				endTime.setInputType(inType);
//				endTime.setSelection(endTime.getText().length());
//
//				builder.setPositiveButton("确  定",
//						new DialogInterface.OnClickListener() {
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//
//								StringBuffer sb = new StringBuffer();
//								sb.append(String.format("%d-%02d-%02d",
//										datePicker.getYear(),
//										datePicker.getMonth() + 1,
//										datePicker.getDayOfMonth()));
//								endTime.setText(sb);
//								dialog.cancel();
//							}
//						});
//			}
//
//			Dialog dialog = builder.create();
//			dialog.show();
//		}
//		return true;
//	}
//
//	/**
//	 * 点击空白处时，隐藏键盘
//	 */
//	@Override
//    public boolean onTouchEvent(MotionEvent event){
//        if(event.getAction()==MotionEvent.ACTION_DOWN){
//            if(PaintProUI.this.getCurrentFocus() != null && PaintProUI.this.getCurrentFocus().getWindowToken() != null){
//                    inputMethodManager.hideSoftInputFromWindow(PaintProUI.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
//            }
//        }
//        return super.onTouchEvent(event);
//    }

}
